package net.hn.hnms.biz.plan.service.impl;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;
import net.hn.hnms.biz.plan.group.service.GroupBigScreenSerevice;
import net.hn.hnms.biz.plan.mapper.CoalmineBigScreenMapper;
import net.hn.hnms.biz.plan.service.CoalmineBigScreenSerevice;
import net.hn.hnms.biz.plan.vo.CoalMiningTotalVo;
import net.hn.hnms.biz.plan.vo.CoalMiningYoyMomVo;
import net.hn.hnms.biz.plan.vo.CoalTypeCategoryVo;
import net.hn.hnms.sys.common.core.constant.Constants;
import net.hn.hnms.sys.common.core.exception.HuaNengException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CoalmineBigScreenSereviceImpl implements CoalmineBigScreenSerevice {


    @Autowired
    private CoalmineBigScreenMapper coalmineBigScreenMapper;

    @Override
    public List<CoalMiningYoyMomVo> getSameRingCompare(Integer type,String mineCode) {
        LocalTime currentTime = LocalTime.now();
        Integer mark = null;
        if (currentTime.isAfter(LocalTime.of(0, 0)) && currentTime.isBefore(LocalTime.of(8, 0))) {
            System.out.println("当前时间在0点和8点之间"+LocalTime.now());
            mark = 2;
        } else {
            System.out.println("当前时间不在0点和8点之间");
            mark = 1;
        }
        DynamicDataSourceContextHolder.push("dws");
        List<CoalMiningYoyMomVo> sameRingCompare = coalmineBigScreenMapper.getSameRingCompare(type,mark,mineCode);
        DynamicDataSourceContextHolder.clear();
        return sameRingCompare;
    }

    @Override
    public List<CoalTypeCategoryVo> getCoaltypecategoryByMineName(String mineName) {
        LocalTime currentTime = LocalTime.now();
        Integer mark = null;
        if (currentTime.isAfter(LocalTime.of(0, 0)) && currentTime.isBefore(LocalTime.of(8, 0))) {
            System.out.println("当前时间在0点和8点之间"+LocalTime.now());
            mark = 2;
        } else {
            System.out.println("当前时间不在0点和8点之间");
            mark = 1;
        }
        DynamicDataSourceContextHolder.push("jygl");
        List<CoalTypeCategoryVo> sameRingCompare = coalmineBigScreenMapper.getCoaltypecategoryByMineName(mark,mineName);
        DynamicDataSourceContextHolder.clear();
        return sameRingCompare;
    }

    @Override
    public Map<String, List<CoalMiningTotalVo>> getTrendProductionAndSale(Integer type, String  mineCode) {
        List<CoalMiningTotalVo> monthOuputVOList = new ArrayList<>();
        LocalTime currentTime = LocalTime.now();
        Integer mark = null;
        if (currentTime.isAfter(LocalTime.of(0, 0)) && currentTime.isBefore(LocalTime.of(8, 0))) {
            System.out.println("当前时间在0点和8点之间"+LocalTime.now());
            mark = 2;
        } else {
            System.out.println("当前时间不在0点和8点之间");
            mark = 1;
        }
        List<String> orderGroup1 = Arrays.asList("总计", "华亭", "扎煤", "陕西", "庆阳");
        List<String> orderGroup2 = Arrays.asList("总计","煤业公司", "北方公司", "蒙东公司");
        List<String> selectedOrder ;
        DynamicDataSourceContextHolder.push("dm");
        if((type == 1 )) {//近10年 煤矿
            monthOuputVOList = coalmineBigScreenMapper.recentlyTenYearsByIndustry(1,mineCode);
            selectedOrder = orderGroup2;
        }else if (type == 2 ) { //近12月  煤矿-------------
            monthOuputVOList = coalmineBigScreenMapper.recentlyTwelveMonthsByIndustry(1,mineCode);
            selectedOrder = orderGroup2;
        }else if(type == 3 ){ //近30天  煤矿
            monthOuputVOList = coalmineBigScreenMapper.recentlyThirtyDaysByIndustry(1,mark,mineCode);
            selectedOrder = orderGroup2;
        }
        else {
            throw new HuaNengException(Constants.FAIL, "参数不正确");
        }
        DynamicDataSourceContextHolder.clear();


        // 按组织名称分组
        Map<String, List<CoalMiningTotalVo>> groupedByOrg = monthOuputVOList.stream()
                .filter(vo -> vo.getOrgShortName() != null)
                .collect(Collectors.groupingBy(CoalMiningTotalVo::getOrgShortName));


        Map<String, List<CoalMiningTotalVo>> sortedGroupedByOrg1 = groupedByOrg.entrySet().stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        entry -> entry.getValue().stream()
                                .sorted(Comparator.comparing(CoalMiningTotalVo::getStYear, Comparator.nullsLast(Comparator.naturalOrder())))
                                .collect(Collectors.toList()),
                        (existing, replacement) -> existing,
                        LinkedHashMap::new
                ));

        // 按 selectedOrder 排序 groupedByOrg 的键
        Map<String, List<CoalMiningTotalVo>> sortedGroupedByOrg = sortedGroupedByOrg1.entrySet().stream()
                .sorted(Map.Entry.comparingByKey(Comparator.comparingInt(selectedOrder::indexOf)))
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (e1, e2) -> e1,
                        LinkedHashMap::new
                ));

        // 打印结果
        sortedGroupedByOrg.forEach((orgName, dataList) -> {
            System.out.println("Organization: " + orgName);
            dataList.forEach(vo -> System.out.println("Date: " + vo.getStYear()));
        });


        return sortedGroupedByOrg;
    }

    @Override
    public CoalMiningTotalVo getDailyOutputStatus(Integer type, String orgCode,boolean flag) {
        DynamicDataSourceContextHolder.push("dm");
        if(type==null||type>3||type<1){
            throw new HuaNengException(Constants.FAIL, "参数不正确");
        }
        LocalTime currentTime = LocalTime.now();
        Integer mark = null;
        if (currentTime.isAfter(LocalTime.of(0, 0)) && currentTime.isBefore(LocalTime.of(8, 0))) {
//            System.out.println("当前时间在0点和8点之间"+LocalTime.now());
            log.info("当前时间在0点和8点之间"+LocalTime.now());
            mark = 2;
        } else {
//            System.out.println("");
            log.info("当前时间不在0点和8点之间");
            mark = 1;
        }
        CoalMiningTotalVo dailyOutputStatus = new CoalMiningTotalVo();
        dailyOutputStatus = coalmineBigScreenMapper.getDailyOutputStatusByOrgCode(type,mark,orgCode);
        if(flag){
            List<CoalMiningYoyMomVo> sameRingCompare = getSameRingCompare(type, orgCode);
            dailyOutputStatus.setCoalMiningYoyMomVoList(sameRingCompare);
        }
        DynamicDataSourceContextHolder.clear();
        return dailyOutputStatus;
    }

    @Override
    public Map<String, List<CoalMiningTotalVo>> getTrendProductionAndSaleByYear(Integer year, String mineCode) {
        List<CoalMiningTotalVo> monthOuputVOList = new ArrayList<>();
        LocalTime currentTime = LocalTime.now();
        Integer mark = null;
        if (currentTime.isAfter(LocalTime.of(0, 0)) && currentTime.isBefore(LocalTime.of(8, 0))) {
            System.out.println("当前时间在0点和8点之间"+LocalTime.now());
            mark = 2;
        } else {
            System.out.println("当前时间不在0点和8点之间");
            mark = 1;
        }
        List<String> orderGroup1 = Arrays.asList("总计", "华亭", "扎煤", "陕西", "庆阳");
        List<String> orderGroup2 = Arrays.asList("总计","煤业公司", "北方公司", "蒙东公司");
        List<String> selectedOrder ;
        DynamicDataSourceContextHolder.push("dm");
        if(year!=null) {//当年的所有月 煤矿
            monthOuputVOList = coalmineBigScreenMapper.getTrendProductionAndSaleByYear(year, mineCode);
            selectedOrder = orderGroup2;

        }else {
            throw new HuaNengException(Constants.FAIL, "参数不正确");
        }
        DynamicDataSourceContextHolder.clear();


        // 按组织名称分组
        Map<String, List<CoalMiningTotalVo>> groupedByOrg = monthOuputVOList.stream()
                .filter(vo -> vo.getOrgShortName() != null)
                .collect(Collectors.groupingBy(CoalMiningTotalVo::getOrgShortName));


        Map<String, List<CoalMiningTotalVo>> sortedGroupedByOrg1 = groupedByOrg.entrySet().stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        entry -> entry.getValue().stream()
                                .sorted(Comparator.comparing(CoalMiningTotalVo::getStYear, Comparator.nullsLast(Comparator.naturalOrder())))
                                .collect(Collectors.toList()),
                        (existing, replacement) -> existing,
                        LinkedHashMap::new
                ));

        // 按 selectedOrder 排序 groupedByOrg 的键
        Map<String, List<CoalMiningTotalVo>> sortedGroupedByOrg = sortedGroupedByOrg1.entrySet().stream()
                .sorted(Map.Entry.comparingByKey(Comparator.comparingInt(selectedOrder::indexOf)))
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (e1, e2) -> e1,
                        LinkedHashMap::new
                ));

        // 打印结果
        sortedGroupedByOrg.forEach((orgName, dataList) -> {
            System.out.println("Organization: " + orgName);
            dataList.forEach(vo -> System.out.println("Date: " + vo.getStYear()));
        });


        return sortedGroupedByOrg;
    }
}
